<template>
  <el-dialog
    class="ba-operate-dialog"
    :close-on-click-modal="false"
    :model-value="baTable.form.operate ? true : false"
    @close="baTable.toggleForm"
  >
    <template #header>
      <div class="title" v-drag="['.ba-operate-dialog', '.el-dialog__header']">
        {{ baTable.form.operate !== "edit" ? "添加" : "编辑" }}
      </div>
    </template>
    <el-scrollbar
      v-loading="baTable.form.loading"
      class="ba-table-form-scrollbar"
    >
      <div
        class="ba-operate-form"
        :class="'ba-' + baTable.form.operate + '-form'"
        :style="'width: calc(100% - ' + baTable.form.labelWidth! / 2 + 'px)'"
      >
        <el-form
          ref="formRef"
          @keyup.enter="baTable.onSubmit(formRef)"
          :model="baTable.form.items"
          label-position="right"
          :label-width="baTable.form.labelWidth + 'px'"
          :rules="rules"
          v-if="!baTable.form.loading"
        >
          <el-form-item label="物料字典">
            <el-input v-model="filterText" placeholder="输入关键字进行过滤" />
            <el-scrollbar
              ref="verticalMenusRef"
              class="vertical-menus-scrollbar"
              style="height: 200px"
            >
              <el-tree
                ref="treeRef"
                :default-checked-keys="
                  baTable.form.operate == 'edit'
                    ? [baTable.form.items.code]
                    : []
                "
                class="tree-border"
                :data="state.bomDOptions"
                :props="defaultProps"
                node-key="code"
                show-checkbox
                @check="handleCheckChange"
                :filter-node-method="filterNode"
              />
            </el-scrollbar>
          </el-form-item>
          <el-form-item label="物料名称" prop="materialName">
            <el-input v-model="baTable.form.items!.materialName" />
          </el-form-item>
          <el-form-item label="物料编码" prop="materialCode">
            <el-input v-model="baTable.form.items!.materialCode" />
          </el-form-item>
          <el-form-item label="缺陷项类型" prop="defectType">
            <el-tree-select
              v-model="baTable.form.items!.defectType"
              :data="state.defectOptions"
              check-strictly
              :props="{
                label: 'dictLabel',
                value: 'dictValue',
                children: 'children',
              }"
              :render-after-expand="false"
              @node-click="defecthandleCheckChange"
            />
          </el-form-item>
          <el-form-item label="缺陷项名称" prop="defectName">
            <el-input v-model="baTable.form.items!.defectName" />
          </el-form-item>
          <el-form-item label="缺陷项编码" prop="defectCode">
            <el-input v-model="baTable.form.items!.defectCode" />
            <div class="block-help">
              格式：物料编码-缺陷名称首字母(1.03.03.0679-WG)
            </div>
          </el-form-item>
        </el-form>
      </div>
    </el-scrollbar>
    <template #footer>
      <div
        :style="'width: calc(100% - ' + baTable.form.labelWidth! / 1.8 + 'px)'"
      >
        <el-button @click="baTable.toggleForm('')">取消</el-button>
        <el-button
          v-blur
          :loading="baTable.form.submitLoading"
          @click="baTable.onSubmit(formRef)"
          type="primary"
        >
          {{ baTable.form.operate === "itemAdd" ? "确定并新增下一项" : "确定" }}
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script lang="ts" setup>
import { reactive, ref, inject, onMounted, watch } from "vue";
import type baTableClass from "@/utils/baTable";
import type { ElForm, FormItemRule, FormRules, ElTree } from "element-plus";
import FormItem from "@/components/formItem/index.vue";
import { getDictData } from "@/utils/common";

const formRef = ref<InstanceType<typeof ElForm>>();
const baTable = inject("baTable") as baTableClass;
const bomD = inject("bomD") as any;
const dictionary = inject("dictionary") as any;
const defect = inject("defect") as any;
const filterText = ref(""); //供应商列表关键词过滤
const treeRef = ref<InstanceType<typeof ElTree>>();

const state: {
  typeOptions: any;
  stationOptions: any;
  processOptions: anyObj[];
  purchaseSettlementOptions: anyObj[];
  purchaseBillingOptions: anyObj[];
  UserDeptOptions: anyObj[];
  supplierOptions: anyObj[];
  processIds: any;
  bomDOptions: anyObj[];
  defectOptions: anyObj[];
} = reactive({
  typeOptions: [], //物料类型列表
  stationOptions: [], //工作中心列表
  processOptions: [], //工序列表
  purchaseSettlementOptions: [], //结算方式列表
  purchaseBillingOptions: [], //开票方式列表
  UserDeptOptions: [], //人员班组列表
  supplierOptions: [], //供应商列表
  processIds: 0,
  bomDOptions: [], //bom字典列表
  defectOptions: [], //缺陷项类型字典列表
});

const defaultProps = {
  children: "children",
  label: "name",
};

// 关键词过滤
const filterNode = (value: string, data: any) => {
  console.log(value, data);
  if (!value) return true;
  return data.name.includes(value);
};

const handleCheckChange = (row: any, node: any) => {
  console.log("row", row, "node", node);
  if (node.checkedKeys.length == 0) {
  } else {
    baTable.form.items!.materialCode = row.code; //物料编码
    baTable.form.items!.materialName = row.name; //物料名称
  }
};

const rules = reactive<FormRules>({
  materialName: [
    { required: true, message: "物料名称不能为空", trigger: "blur" },
  ],
  materialCode: [
    { required: true, message: "物料编码不能为空", trigger: "blur" },
  ],
  defectType: [
    { required: true, message: "缺陷项类型不能为空", trigger: "blur" },
  ],
  defectName: [
    { required: true, message: "缺陷项名称不能为空", trigger: "blur" },
  ],
  process: [{ required: true, message: "工序号不能为空", trigger: "blur" }],
});

//获取结算方式/开票方式字典
const getMenuStatus = () => {
  //采购单结算方式
  if (
    JSON.stringify(dictionary.moreTags) == "{}" ||
    !JSON.stringify(dictionary.moreTags["defectType"])
  ) {
    dictionary.getDictInfo("sys_quality_defect").then((res: any) => {
      dictionary.moreTags["defectType"] = getDictData(res);
      dictionary.moreTags["defectTypeOrigin"] = res;
      console.log("获取缺陷项类型的字典", dictionary.moreTags);
    });
  } else {
    state.defectOptions = dictionary.moreTags["defectTypeOrigin"];
    console.log("获取缺陷项类型的字典", state.defectOptions);
  }
};
//获取结算方式/开票方式字典
getMenuStatus();

//选择缺陷类型
const defecthandleCheckChange = (row: any) => {
  console.log("row", row);
  baTable.form.items!.defectName = row.dictLabel; //缺陷项名称
};

//计算两个总价
const getSumPrice = () => {
  //含税总价
  baTable.form.items!.taxTotalPrice =
    baTable.form.items!.purchaseQuantity * baTable.form.items!.taxUnitPrice;
  //不含税总价
  baTable.form.items!.totalPriceWithoutTax =
    baTable.form.items!.purchaseQuantity *
    baTable.form.items!.unitPriceWithoutTax;
};

//采购人员
const personChange = (val: any) => {
  console.log("采购人员", val);
  baTable.form.items!.purchaserName = val.nickName; //采购人员名称
  baTable.form.items!.purchaserId = val.userId; //采购人员id
};

onMounted(() => {
  //获取物料字典数据
  bomD.getBomDictByRole().then((res: any) => {
    state.bomDOptions = res;
  });
  //获取人员(采购)
  // User.getUsers({
  //   pageSize: 10000,
  // }).then((res: any) => {
  //   state.UserDeptOptions = res.rows;
  // });
  //获取供应商列表数据
  // supplier.getSupplier().then((res: any) => {
  //   state.supplierOptions = res.rows;
  // });

  setTimeout(() => {});
});

watch(filterText, (val) => {
  treeRef.value!.filter(val);
});
</script>
<style lang="scss" scoped>
.el-scrollbar {
  overflow: auto;
  position: relative;
  height: 100%;
  width: 100%;

  .el-scrollbar__wrap {
    overflow: auto;
    height: 100%;
  }
}
.vertical-menus-scrollbar {
  border: 1px solid #e5e6e7;
}
.tree-border {
  width: 100%;
  margin-top: 5px;
  border-radius: 4px;
}
</style>
